﻿
Partial Class MasterPage
    Inherits System.Web.UI.MasterPage
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Request.QueryString("logout") Is Nothing Then
            FormsAuthentication.SignOut()
            Response.Redirect("~/home.aspx", False)
        End If
        'assign menu items to variables
        Dim menuItem_register As MenuItem = Me.MainMenu.FindItem("Register")
        Dim menuItem_login As MenuItem = Me.MainMenu.FindItem("Login")
        Dim menuItem_logout As MenuItem = Me.MainMenu.FindItem("Logout")
        Dim menuItem_addsong As MenuItem = Me.MainMenu.FindItem("Add Song")

        'check if current user is authenticated
        If Page.User.Identity.IsAuthenticated Then
            'remove login and register menu items (if present)
            If Not menuItem_register Is Nothing Then Me.MainMenu.Items.Remove(menuItem_register)
            If Not menuItem_login Is Nothing Then Me.MainMenu.Items.Remove(menuItem_login)
            'add logout and add song menu items if absent
            If menuItem_logout Is Nothing Then
                menuItem_logout = New MenuItem("Logout")
                menuItem_logout.NavigateUrl = "~/home.aspx?logout=true"
                Me.MainMenu.Items.Add(menuItem_logout)
            End If
            If menuItem_addsong Is Nothing Then
                menuItem_addsong = New MenuItem("Add Song")
                menuItem_addsong.NavigateUrl = "~/editSong.aspx"
                menuItem_addsong.ToolTip = "Add a song!"
                Me.MainMenu.Items.Add(menuItem_addsong)
            End If
            'Add "logged in as" text
            Me.div_loggedInAs.InnerText = "Logged in as " & Page.User.Identity.Name
        Else
            'remove logout and add song menu items if present
            If Not menuItem_logout Is Nothing Then Me.MainMenu.Items.Remove(menuItem_logout)
            If Not menuItem_addsong Is Nothing Then Me.MainMenu.Items.Remove(menuItem_addsong)
            'add register and login menu items if absent
            If menuItem_login Is Nothing Then
                menuItem_login = New MenuItem("Login")
                menuItem_login.NavigateUrl = "~/login.aspx"
                menuItem_login.ToolTip = "Login to the site"
                Me.MainMenu.Items.Add(menuItem_login)
            End If
            If menuItem_register Is Nothing Then
                menuItem_register = New MenuItem("Register")
                menuItem_register.NavigateUrl = "~/register.aspx"
                menuItem_register.ToolTip = "Register as a new user"
                Me.MainMenu.Items.Add(menuItem_register)
            End If
            'Remove "logged in as" text
            Me.div_loggedInAs.InnerText = ""
        End If
    End Sub
End Class

